from sqlalchemy.ext.asyncio import AsyncSession
from typing import List
from config.constant import CommonConstant
from exceptions.exception import ServiceException
from module_admin.entity.vo.common_vo import CrudResponseModel
from module_admin.system.dao.student_dao import StudentDao
from module_admin.system.entity.vo.student_vo import DeleteStudentModel, StudentModel, StudentPageQueryModel
from utils.common_util import CamelCaseUtil
from utils.excel_util import ExcelUtil


class StudentService:
    """
    学生模块服务层
    """

    @classmethod
    async def get_student_list_services(
        cls, query_db: AsyncSession, query_object: StudentPageQueryModel, is_page: bool = False
    ):
        """
        获取学生列表信息service

        :param query_db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 学生列表信息对象
        """
        student_list_result = await StudentDao.get_student_list(query_db, query_object, is_page)

        return student_list_result

    @classmethod
    async def check_id_unique_services(cls, query_db: AsyncSession, page_object: StudentModel):
        """
        检查ID是否唯一service

        :param query_db: orm对象
        :param page_object: 学生对象
        :return: 校验结果
        """
        id = -1 if page_object.id is None else page_object.id
        student = await StudentDao.get_student_detail_by_info(query_db, StudentModel(id=page_object.id))
        if student and student.id != id:
            return CommonConstant.NOT_UNIQUE
        return CommonConstant.UNIQUE

    @classmethod
    async def add_student_services(cls, query_db: AsyncSession, page_object: StudentModel):
        """
        新增学生信息service

        :param query_db: orm对象
        :param page_object: 新增学生对象
        :return: 新增学生校验结果
        """
        if not await cls.check_id_unique_services(query_db, page_object):
            raise ServiceException(message=f'新增学生{page_object.id}失败，ID已存在')
        try:
            await StudentDao.add_student_dao(query_db, page_object)
            await query_db.commit()
            return CrudResponseModel(is_success=True, message='新增成功')
        except Exception as e:
            await query_db.rollback()
            raise e

    @classmethod
    async def edit_student_services(cls, query_db: AsyncSession, page_object: StudentModel):
        """
        编辑学生信息service

        :param query_db: orm对象
        :param page_object: 编辑学生对象
        :return: 编辑学生校验结果
        """
        edit_student = page_object.model_dump(exclude_unset=True, exclude={})
        student_info = await cls.student_detail_services(query_db, page_object.id)
        if student_info.id:
            if not await cls.check_id_unique_services(query_db, page_object):
                raise ServiceException(message=f'修改学生{page_object.id}失败，ID已存在')
            try:
                await StudentDao.edit_student_dao(query_db, edit_student)
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='更新成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='学生不存在')

    @classmethod
    async def delete_student_services(cls, query_db: AsyncSession, page_object: DeleteStudentModel):
        """
        删除学生信息service

        :param query_db: orm对象
        :param page_object: 删除学生对象
        :return: 删除学生校验结果
        """
        if page_object.ids:
            id_list = page_object.ids.split(',')
            try:
                for id in id_list:
                    await StudentDao.delete_student_dao(query_db, StudentModel(id=id))
                await query_db.commit()
                return CrudResponseModel(is_success=True, message='删除成功')
            except Exception as e:
                await query_db.rollback()
                raise e
        else:
            raise ServiceException(message='传入ID为空')

    @classmethod
    async def student_detail_services(cls, query_db: AsyncSession, id: int):
        """
        获取学生详细信息service

        :param query_db: orm对象
        :param id: ID
        :return: ID对应的信息
        """
        student = await StudentDao.get_student_detail_by_id(query_db, id=id)
        if student:
            result = StudentModel(**CamelCaseUtil.transform_result(student))
        else:
            result = StudentModel(**dict())

        return result

    @staticmethod
    async def export_student_list_services(student_list: List):
        """
        导出学生信息service

        :param student_list: 学生信息列表
        :return: 学生信息对应excel的二进制数据
        """
        # 创建一个映射字典，将英文键映射到中文键
        mapping_dict = {
            'name': '姓名',
            'id': 'ID',
        }
        binary_data = ExcelUtil.export_list2excel(student_list, mapping_dict)

        return binary_data
